package org.leviatan.dataharbour.gui.swingmodels;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import org.leviatan.dataharbour.core.model.PersistenceResource;
import org.leviatan.dataharbour.gui.RuntimeContext;

public class TreeMdlPersistenceResource extends DefaultTreeModel {

	private static final long serialVersionUID = 1282387976802173100L;
	
	private DefaultMutableTreeNode theRoot;
	
	private HashMap<String, TreeNodeMdlPersistenceResource> treeNodeModels;
	
	
	public TreeMdlPersistenceResource() {
		super(new DefaultMutableTreeNode("Persistence resources"));
		this.theRoot = (DefaultMutableTreeNode) this.getRoot();
		//RuntimeContext.defTree = this;
		
		this.treeNodeModels = new HashMap<String, TreeNodeMdlPersistenceResource>();
		this.buildTree();
	}

	private void buildTree() {
		HashMap persResMap = RuntimeContext.dataHarbourService.getAllPersistenceResources();
		Vector<PersistenceResource> persRes = (Vector<PersistenceResource>) persResMap.values();
		
		//DataHarbourServiceProxy proxy = RuntimeContext.dataHarbourService;
		
		TreeNodeMdlPersistenceResource nodeMdlPersRes;
		
		// iterate persistence resources
		for (Iterator i = persRes.iterator(); i.hasNext(); ) {
			PersistenceResource persResource = (PersistenceResource) i.next();
			
			nodeMdlPersRes = new TreeNodeMdlPersistenceResource(persResource);
			this.theRoot.add(nodeMdlPersRes);
			this.treeNodeModels.put(nodeMdlPersRes.getId(), nodeMdlPersRes);
		}
	}
	
	
	public TreeNodeMdlPersistenceResource getNodeModel(String id) {
		return this.treeNodeModels.get(id);
	}
	
	public void reload() {
		this.theRoot.removeAllChildren();
		this.treeNodeModels.clear();
		this.buildTree();
		super.reload();
	}

	public DefaultMutableTreeNode getTheRoot() {
		return theRoot;
	}

	public void setTheRoot(DefaultMutableTreeNode theRoot) {
		this.theRoot = theRoot;
	}
		
}
